<?php
/**
 * 简单的 csv 操作类
 * @auther 41412754@qq.com
 */
class csv {
	
	public $row;
	public $body;
	
	public function __construct()
	{
		self::reset();
	}
	
	/**
	 * 复位/初始化
	 */
	public function reset()
	{
		$this->row = 0;
		$this->body = array();
	}
	
	/**
	 * 设置单元格值
	 * @param $str
	 */
	public function cell( $str = '' )
	{
		if ( $str .= '' !== '' )
		{
			if ( strpos( $str, '"' ) !== false ) $str = str_replace( '"', '""', $str );
			if ( strpos( $str, ',' ) !== false or strpos( $str, "\n" ) !== false or strpos( $str, "\r" ) !== false or strpos( $str, '0' ) === 0 ) $str = '"' . $str . '"';
			if ( strpos( $str, '"0' ) === 0 ) $str = '=' . $str;
		}
		$this->body[$this->row][] = iconv( 'utf-8', 'gb2312', $str );
	}
	
	/**
	 * 新启一行
	 */
	public function newline()
	{
		$key = $this->body[$this->row] ? max( array_keys( $this->body[$this->row] ) ) : 0;
		$this->body[$this->row][$key] .= "\n";
		$this->row ++;
	}
	
	/**
	 * 整合数据为csv格式
	 */
	public function integrate()
	{
		foreach ( $this->body as $row )
		{
			$body .= implode( ',', $row );
		}
		return $this->body = $body;
	}
	
	/**
	 * 输出 csv 文件
	 * @param $filename
	 */
	public function export( $filename = null )
	{
		self::integrate();
		
		if ( ! $filename ) $filename = date( 'YmdHis' );
		$filename .= '.csv';
		
		header( "Content-Type: application/csv" );
		header( "Content-Disposition: attachment; filename=$filename" );
		header( "Pragma: no-cache" );
		header( "Expires: 0" );
		echo $this->body;
	}
	
	/**
	 * 导入 csv 文件<br />
	 * 先上传并获取返回值传参给import
	 * @param $file
	 * @link http://hi.baidu.com/tylergong/item/8552514331147593833ae148
	 */
	public function import( $file )
	{
		if ( empty( $file ) )
		{
			$this->error = '没有找到上传的文件';
			return false;
		}
		$fileName = $file['name'];
		$fileExt = strtolower( substr( strrchr( $fileName, '.' ), 1 ) );
		if ( $fileExt !== 'csv' )
		{
			$this->error = '仅支持 csv 格式';
			return false;
		}
		/* 将文件按行读入数组，逐行进行解析 */
		$csvfile = fopen( $file['tmp_name'], 'r' );
		$line = 0;
		while ( $row = fgetcsv( $csvfile ) )
		{
			if ( $line == 0 )
			{
				$key = $row;
				$size = count( $row );
			}
			else
			{
				for ( $i = 0; $i < $size; $i ++ )
					$tmp[$key[$i]] = mysql_real_escape_string( iconv( 'gb2312', 'utf-8', $row[$i] ) );
				
				$csv[$line - 1] = (object)$tmp;
			}
			$line ++;
		}
		fclose( $csvfile );
		return $csv;
	}
}
